from flask import Blueprint, render_template, request, redirect, url_for, session, Response
import time
from utils.captcha import generate_captcha
from utils.db import verify_user

# 创建蓝图，指定模块名和URL前缀
auth_bp = Blueprint('auth', __name__, url_prefix='/auth', template_folder='../templates/auth')

# 验证码路由（属于认证模块）
@auth_bp.route('/captcha')
def get_captcha():
    image_buf, code = generate_captcha()
    session['captcha'] = code
    session['captcha_expire'] = time.time() + 300  # 5分钟有效期
    return Response(image_buf, mimetype='image/png')

# 登录路由
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        user_captcha = request.form.get('captcha', '').upper()
        
        # 验证逻辑（省略部分代码，与之前相同）
        error = None
        if not username:
            error = '请输入用户名'
        elif not password:
            error = '请输入密码'
        elif user_captcha != session.get('captcha').upper():
            error = '验证码错误'
        
        if error:
            return render_template('login.html', error=error)
        
        # 验证用户
        if verify_user(username, password):
            session['logged_in'] = True
            session['username'] = username
            return redirect(url_for('main.home'))  # 跳转到主模块的主页
        else:
            return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

# 登出路由
@auth_bp.route('/logout')
def logout():
    session.pop('logged_in', None)
    session.pop('username', None)
    session.clear()
    session.modified = True
    return redirect(url_for('auth.login'))  # 跳回登录页
